package com.heo.task.thread;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import java.io.IOException;
import org.apache.log4j.Logger;
import com.heo.task.SendTaskQueuePriority;
import com.heo.util.NettyChannelMapUtils;


public class TaskWaterThared implements Runnable {

	private static final Logger logger = Logger
			.getLogger(TaskWaterThared.class);

	private Channel channel = null;
	private String message;
	private String imei;
	private String appId;
	private WaterSendInfo waterSendInfo;

	public TaskWaterThared(WaterSendInfo waterSendInfo) {
		this.imei = waterSendInfo.getImei();
		this.appId = waterSendInfo.getAppId();
		this.channel = NettyChannelMapUtils.get(appId, imei);
		this.message = waterSendInfo.getSm();
		this.waterSendInfo = waterSendInfo;
	}
	
	public WaterSendInfo getWaterSendInfo() {
		return waterSendInfo;
	}

	public void run() {
		try {
			if (channel != null) {
				if(channel.isActive() && channel.isWritable()) {
					channel.writeAndFlush(message + "\n").addListener(new ChannelFutureListener() {
						@Override
					    public void operationComplete(ChannelFuture future) throws Exception {
					    	logger.info(imei + "" + message + "消息发送结果=" + future.isSuccess());
					    }
					});
				}
			}else {
				logger.info("nettyWaterHandle为空，消息发送失败，不重发");
			}
		} catch (Exception e) {
			logger.error("TaskWaterThared第" + waterSendInfo.getSc() + "，线程处理消息异常 = " + e.getMessage() + "，消息内容=" + waterSendInfo.getSm());
			if (waterSendInfo.getSc() < waterSendInfo.getSs()) {
				waterSendInfo.setSt(System.currentTimeMillis() + waterSendInfo.getSl());
				try {
					SendTaskQueuePriority.getInstance().addCallBackMsg(waterSendInfo);
				} catch (IOException e1) {
				}
			}
		}
	}
}
